<template>
  <div class="forum-page">
    <el-dialog title="编辑帖子" :visible.sync="editDialogVisible" width="80%">
      <el-form :model="editForm">
        <el-form-item label="帖子标题" :label-width="formLabelWidth">
          <el-input v-model="editForm.postTitle" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="帖子内容" :label-width="formLabelWidth">
          <editor type="textarea" v-model="editForm.postContent"></editor>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updatePost(editForm)"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-row :gutter="12" style="margin-bottom: 20px; align-items: center">
      <el-col :span="4">
        <h1>论坛</h1>
        <el-input
          placeholder="搜索...(标题)"
          prefix-icon="el-icon-search"
          v-model="queryParams.postTitle"
          clearable
          @input="onSearchInput"
        >
        </el-input>

        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <div class="post-cards">
          <el-card
            class="post-card"
            v-for="post in posts"
            :key="post.id"
            :body-style="{ padding: '20px' }"
            @click.native="goToPostDetail(post)"
          >
            <div class="post-header">
              <h3>{{ post.postTitle }}</h3>
              <div>{{ post.userName }} · {{ post.createdAt }}</div>
            </div>
            <div class="post-actions">
              <el-button
                type="text"
                icon="el-icon-view"
                @click.stop="goToPostDetail(post)"
                >查看详情</el-button
              >

              <template v-if="post.userId === currentUserId">
                <el-button
                  type="text"
                  icon="el-icon-edit"
                  @click.stop="editPost(post.postId)"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  @click.stop="deletePost(post.postId)"
                  >删除</el-button
                >
              </template>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-pagination
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-size="10"
          layout="prev, pager, next"
          :total="10"
        >
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  listPosts,
  getPosts,
  delPosts,
  addPosts,
  updatePosts,
} from "@/api/teahouse/posts";
import _ from "lodash";
export default {
  name: "ForumPage",
  data() {
    return {
      currentUserId: null,
      searchQuery: "",
      posts: [],
      currentPage: 1,
      postsList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userName: null,
        postTitle: null,
        createdAt: null,
      },
      form: {
        userId: null,
        postTitle: null,
        postContent: null,
      },
      editDialogVisible: false,
      editForm: {
        postId: null,
        postTitle: "",
        postContent: "",
      },
      formLabelWidth: "120px",
    };
  },
  mounted() {
    this.getList();
    this.debouncedQuery = _.debounce(this.handleQuery, 300);
    this.currentUserId = this.$store.state.user.id;
  },
  methods: {
    getList() {
      //查询所有的帖子，前端再筛选状态为通过的帖子
      listPosts(this.queryParams).then((response) => {
        // 过滤出 status 为 1(通过) 的项
        this.postsList = response.rows.filter((post) => post.status === 1);
        this.posts = this.postsList;
      });
    },
    handlePageChange(newPage) {
      console.log("Page changed to", newPage);
    },
    likePost(postId) {
      console.log("Liked post", postId);
    },
    replyToPost(postId) {
      console.log("Reply to post", postId);
    },
    goToPostDetail(post) {
      // console.log(post);
      const id = post.postId;
      this.$router.push({
        path: "/postDetail",
        query: { id }, //
      });
    },
    //新增帖子
    add(form) {
      addPosts(form).then((response) => {
        this.$modal.msgSuccess("新增成功");
        this.getList();
      });
    },
    editPost(postId) {
      getPosts(postId).then((post) => {
        if (post.code == 200) {
          const { postTitle, postContent } = post.data;
          this.editForm = {
            postId,
            postTitle,
            postContent,
          };
          this.editDialogVisible = true;
        } else {
          this.$message.error("获取帖子信息失败");
        }
      });
    },

    updatePost(form) {
      updatePosts(form)
        .then(() => {
          this.$message.success("帖子更新成功");
          this.editDialogVisible = false;
          this.getList();
        })
        .catch((error) => {
          this.$message.error("更新失败");
        });
    },
    deletePost(postId) {
      this.$confirm("此操作将永久删除该帖子, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delPosts(postId).then(() => {
            this.$message.success("删除成功");
            this.getList(); // 刷新列表
          });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    onSearchInput() {
      this.debouncedQuery();
    },
    navigateToCreatePost() {
      this.$router.push({ path: "/share/create" });
    },
  },
};
</script>

<style>
.forum-page {
  width: 80%;
  margin: 0 auto;
}

.post-cards {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.post-card {
  transition: box-shadow 0.3s;
}

.post-card:hover {
  box-shadow: 0 0 11px rgba(0, 0, 0, 0.26);
  cursor: pointer;
}

.post-header h3 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.post-header div {
  font-size: 14px;
  color: #999;
}

.post-content p {
  color: #666;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-actions {
  margin-top: 20px;
  display: flex;
  align-items: center;
}
</style>
